package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.OrderSetting;
import com.itheima.entity.Result;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: OrderSettingController
 * @Author: Solomon
 * @Date: 2020/7/7 15:43
 * @Description:
 */
@RestController
@RequestMapping("/orderSetting")
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    //文件上传,实现预约设置数据批量导入
    @RequestMapping("/upload")
    public Result upload(@RequestBody MultipartFile excelFile){
        try {
            //POI解析excel表格,返回的是每一行的数据，因为每一行中都有单元格，一行的单元格组成一个OrderSetting对象
            List<String[]> readExcel = POIUtils.readExcel(excelFile);

            //传入的是字符串数组，需要转成OrderSetting对象
            List<OrderSetting> orderSettingList = new ArrayList<>();
            for (String[] strings : readExcel) {
                //得到数组中的元素，赋值给orderSetting对象
                String orderDate = strings[0];
                String number = strings[1];

                OrderSetting orderSetting = new OrderSetting(new Date(orderDate),Integer.parseInt(number));

                orderSettingList.add(orderSetting);
            }

            orderSettingService.add(orderSettingList);

            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            return new Result(false,MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }

    //根据月份查询当前月的预约设置信息
    @RequestMapping("/findOrderSettingByMonth")
    public Result findOrderSettingByMonth(String date){//date的格式为：2020-7
        try {
            //这里的泛型没有声明为orderSetting，是因为前台页面需要的date只是日期，
            // 而我们后台的date类型包含年月日等详细信息，所以我们就需要灵活的进行页面数据的传递
            List<Map> orderSettingList = orderSettingService.findOrderSettingByMonth(date);
            return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,orderSettingList);
        } catch (Exception e) {
            return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    //基于日历修改预约设置信息
    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        try {
            orderSettingService.editNumberByDate(orderSetting);
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
    }
}
